package com.github.m6d21.sso.service.login.impl;

import static com.github.m6d21.sso.support.enums.StatusCode.LOGIN_ERROR;
import static com.github.m6d21.sso.support.enums.StatusCode.REQUEST_PARAM_ERROR;

import com.github.m6d21.sso.core.annotation.Crypt;
import com.github.m6d21.sso.core.annotation.Encrypt;
import com.github.m6d21.sso.core.annotation.Login;
import com.github.m6d21.sso.core.exception.BusinessException;
import com.github.m6d21.sso.core.exception.LoginException;
import com.github.m6d21.sso.core.exception.ParamException;
import com.github.m6d21.sso.model.user.entity.User;
import com.github.m6d21.sso.service.login.ILoginService;
import com.github.m6d21.sso.service.user.IUserService;
import com.github.m6d21.sso.support.enums.StatusCode;
import com.github.m6d21.sso.support.session.SsoSessionHolder;
import com.github.m6d21.sso.support.token.SsoTokenHelper;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 *<p>
 *登录接口
 *</p>
 *
 * @author liuyang
 * @date 2018/12/8 Sat 22:50:00
 * @since 1.0.0
 */
@Service("loginService")
public class LoginServiceImpl implements ILoginService {

    @Resource
    private IUserService userService;

    @Login
    @Crypt
    @Override
    public User login(String username, @Encrypt String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new ParamException(REQUEST_PARAM_ERROR.getCode(), "login(): 用户名以及密码不能为空");
        }
        List<User> users = userService.findByUsernameAndPassword(username, password);
        if (CollectionUtils.isEmpty(users)) {
            throw new LoginException(LOGIN_ERROR.getCode(), "用户名或密码错误");
        }
        return users.get(0);
    }

    @Override
    public void logout() {
        String token = SsoSessionHolder.getToken();
        if (StringUtils.isNotEmpty(token)) {
            //清除缓存
            SsoTokenHelper.clearToken(token);
        }
        //清空session
        SsoSessionHolder.clear();
    }

    @Crypt
    @Override
    public Boolean register(@Encrypt User user) {
        if (null == user) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "用户信息不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "用户名不能为空");
        }
        if (StringUtils.isBlank(user.getDisplayName())) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "昵称不能为空");
        }
        if (StringUtils.isBlank(user.getPassword())) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "密码不能为空");
        }
        if (userService.exist(user.getUsername())) {
            throw new BusinessException(StatusCode.FAIL.getCode(), "用户名已存在");
        }
        User dbUser = userService.saveUser(user);
        return dbUser != null;
    }
}
